//
//  WSComposeController.swift
//  微博
//
//  Created by 武莎莎 on 15/9/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class WSComposeController: UIViewController,UITextViewDelegate {
    
    private var toolBarBottomConstraint:NSLayoutConstraint?
    private var textViewBottomConstraint:NSLayoutConstraint?
    private var pictureViewHeightConstraint:NSLayoutConstraint?
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
        
        // MARK: 通知实现 键盘弹出时，toolBar 仍在键盘的上面
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    // MARK:输入表情符号
    @objc private func switchEmoticonKeyboard() {
        print("输入表情符号")
        // TODO: 
//        if (textView.inputView == nil) {
//            textView.inputView = emoticonView.view
//        }
//        emoticonViewModle.loadPackages()
    }
    // MARK:选择图片
    @objc private func selectImage(){
        print("点击了选择图片")
        // 约束不用的使用要remove掉，设为nil 不可以
        view.removeConstraint(textViewBottomConstraint!)

        pictureViewHeightConstraint?.constant = UIScreen.mainScreen().bounds.height * 0.6

        textViewBottomConstraint = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomConstraint!)

        view.addConstraint(pictureViewHeightConstraint!)

        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    @objc private func keyboardChange(notification:NSNotification) {
        print(notification)
        // 获取键盘的最终frame
        let endY = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue.origin.y
        
        let h = -UIScreen.mainScreen().bounds.height + endY
         self.toolBarBottomConstraint?.constant = h
        UIView.animateWithDuration(0.25) { () -> Void in
           
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 没有选择图片的时候，才弹出键盘
        if pictureViewHeightConstraint?.constant == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    func textViewDidChange(textView: UITextView) {
        print("textViewDidChange")
        // MARK: 输入文字时占位符隐藏
        placeholderLbl.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendblog() {
        print("发送微博")
    }
    // MARK: 设置UI
    override func loadView() {
        // 先给控制器创建一个view
        view = UIView()
        // 关闭自动调整滚动视图缩进
        automaticallyAdjustsScrollViewInsets = false

        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavBar()
        prepareTextView()
        preparePictureView()
        prepareToolBar()
    }
    private func preparePictureView() {
        // 添加子控制器
        // 响应者链条出现问题，一般都是忘了添加子控制器
        addChildViewController(pictureVC)
        // 添加collectionViewController 的view
        view.insertSubview(pictureVC.view, belowSubview: toolBar)
        
        // 添加约束
        let w = UIScreen.mainScreen().bounds.size.width
        let h: CGFloat = 0 //UIScreen.mainScreen().bounds.height * 0.6
        let cons = pictureVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(w, h))
        
        //记录照片视图的高度约束
        pictureViewHeightConstraint = pictureVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    private func prepareTextView() {
        // 文本
        view.addSubview(textView)
        textView.textColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(16)
        
        let viewsDict : [String : AnyObject] = ["tv":textView,"tb":toolBar,"tp":topLayoutGuide]
        textView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewsDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tp]-0-[tv]", options: [], metrics: nil, views: viewsDict))
        // 记录下textView的底部约束
        textViewBottomConstraint = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomConstraint!)
        // 始终显示垂直弹性效果
        textView.alwaysBounceVertical = true
        
        textView.addSubview(placeholderLbl)
        placeholderLbl.frame = CGRect(origin: CGPointMake(5, 8), size:placeholderLbl.bounds.size)
    }
    
    private func prepareToolBar() {
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        let w = UIScreen.mainScreen().bounds.width
        
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 44))
        toolBarBottomConstraint = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    
        let itemSetting = [["imageName":"compose_toolbar_picture","action":"selectImage"],
            ["imageName":"compose_mentionbutton_background"],
            ["imageName":"compose_trendbutton_background"],
            ["imageName":"compose_emoticonbutton_background","action":"switchEmoticonKeyboard"],
            ["imageName":"compose_addbutton_background"]]
        
        var toolBarItems = [UIBarButtonItem]()
        
        for dict in itemSetting {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"])
            toolBarItems.append(item)
            toolBarItems.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        toolBarItems.removeLast()
        toolBar.items = toolBarItems
    }
    private func prepareNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendblog")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let navTitleView = UIView(frame: CGRectMake(0, 0, 200, 32))
        
        let titleLbl = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLbl = UILabel(title: WSUserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.darkGrayColor(), fontSize: 14)
        navTitleView.addSubview(titleLbl)
        navTitleView.addSubview(nameLbl)
        
        titleLbl.ff_AlignInner(type: ff_AlignType.TopCenter, referView: navTitleView, size:nil)
        nameLbl.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: navTitleView, size: nil)
        
        self.navigationItem.titleView = navTitleView
    }
    // MARK: 懒加载控件
    private lazy var toolBar = UIToolbar()
    private lazy var textView = UITextView()
    private lazy var pictureVC = WSSelectPicture()
    private lazy var placeholderLbl:UILabel = UILabel(title: "分享新鲜事", color: UIColor.lightGrayColor(), fontSize: 16)
    private lazy var emoticonView:WSEmoticonKeyboard = WSEmoticonKeyboard { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    private lazy var emoticonViewModle:WSEmoticonViewModel = WSEmoticonViewModel()
}
